<template>
  <view>
    <web-view
      v-if="!showBuild"
      :src="webviewUrl"
      @load="handleLoad"
      @error="handleError"
      @message="onMessage"
    ></web-view>
    <Build :title="title" v-else></Build>
  </view>
</template>

<script lang="ts" setup>
  import Build from './build.vue'
  import { getWebviewAuth } from '@/api/auth'
  import config from '@/config'
  import enpt from '@/encrypt/encrypt'
  import store from '@/store'
  import { msg, showModal } from '@/utils/tools'
  import {
    onLoad,
    onShareAppMessage,
    onShow,
    onUnload,
  } from '@dcloudio/uni-app'
  import { computed, Ref, ref } from 'vue'
  import {
    CURRENT_WEB_OPWENED,
    THREE_PART_LOGIN_DATA,
  } from '@/utils/storageTypes'
  import { useOnMsg } from '../../hooks/useOnMsg'

  const webviewUrl = ref('')
  const tgt = computed(() => store.state.user.TGT)
  const showBuild = ref(false)
  const options = ref({
    url: '',
    auth: 0,
  })
  const onErrorData: Ref<{
    url: string
    auth: number
  } | null> = ref(null)

  const current = uni.getStorageSync(CURRENT_WEB_OPWENED)

  let shareMenuInfo: Ref<CustomShareAppMessage> = ref({})

  function conbineShareMessage(option: ShareAppMessageOption) {
    if (shareMenuInfo.value.path) {
      return {
        imageUrl: shareMenuInfo.value.imageUrl,
        title: shareMenuInfo.value.title,
        path: `pages/index/index?url=${encodeURIComponent(
          shareMenuInfo.value.path
        )}&auth=${shareMenuInfo.value.authType}&sensitiveType=${
          shareMenuInfo.value.sensitiveType
        }`,
      }
    }

    return {
      imageUrl: current.shareImg || '',
      title: current.shareTitle || '',
      path: `/pagePublic/public/webview?url=${encodeURIComponent(
        option.webViewUrl || options.value.url
      )}&auth=${options.value.auth}`,
    }
  }

  onShareAppMessage((option) => {
    return conbineShareMessage(option)
  })

  onShow(() => {
    if (onErrorData.value) {
      setWebUrl(onErrorData.value.url, onErrorData.value.auth)
    }
  })

  onLoad((option) => {
    // option.url = 'http://192.168.0.108:8888/?tfsmy_source=tfsmy_mini#/'
    uni.showLoading({
      title: '加载中',
    })

    uni.$on('modifyShareMessage', (params: CustomShareAppMessage) => {
      shareMenuInfo.value = params
    })

    options.value.url = option?.url || ''
    options.value.auth = option?.auth || 0
    setWebUrl(option?.url || '', option?.auth)
    // #ifdef MP-WEIXIN
    uni.showShareMenu({
      menus: ['shareAppMessage', 'shareTimeline'],
    })
    // #endif
  })

  onUnload(() => {
    uni.$off('modifyShareMessage')
  })

  const setWebUrl = async (url: string, auth = 0) => {
    if (!url) {
      await msg('配置服务错误')
      return uni.navigateBack({})
    }

    url = decodeURIComponent(url)
    console.log('配置服务url：', url)

    if (!+auth) {
      uni.hideLoading()
      return (webviewUrl.value = url)
    }

    try {
      // const { data: rsaData, code } = await getWebviewAuth()
      // const publicKey = rsaData.publicKey
      // const data = {
      //   cityCode: config.cityCode,
      //   url: url,
      //   tgt: tgt.value || '',
      //   token: rsaData.token,
      // }
      // console.log(data, rsaData)

      // if (!publicKey) {
      //   console.log('获取公钥失败')
      //   await msg('服务器错误')
      //   return uni.navigateBack({})
      // }
      // const newdata = enpt.AESRSAencrypt(JSON.stringify(data), publicKey)
      // const newparams = newdata.data
      // const newKey = encodeURIComponent(newdata.key) //url编码
      uni.hideLoading()

      webviewUrl.value = `${
        config.uni_app_web_api_url
      }/auth/wx/deliveryVoucher?redirectUrl=${url}&tgt=${
        uni.getStorageSync(THREE_PART_LOGIN_DATA).tgt || ''
      }`

      console.log('跳转url', webviewUrl.value)

      onErrorData.value = null
    } catch (e) {
      //TODO handle the exception
      console.log('-----失败跳转地址', options.value)
      onErrorData.value = options.value
    }
  }

  const title = ref('')
  const handleError = (e: any) => {
    console.log(e)
    showBuild.value = true
    uni.hideLoading()
    title.value = '出错了，请联系管理员重试'
  }

  const handleLoad = async () => {
    uni.hideLoading()
  }

  const onMessage = async (e: any) => {
    const data = e.detail.data[0]
    useOnMsg(data)
  }
</script>
